package sicnu.cs.ich.common.services.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import sicnu.cs.ich.common.services.ISendMailService;


/**
 * @author CaiKe
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SendMailServiceImpl implements ISendMailService {

    private final JavaMailSenderImpl javaMailSender;
    private final RedisService redisService;

    @Value("${spring.mail.username:''}")
    private String sender;

    @Override
    public void sendEmail(SimpleMailMessage simpleMailMessage) throws MailSendException {
        // 发送邮件
        try {
            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            throw new MailSendException("邮件发送失败！");
        }
    }

    /**
     * 验证邮箱验证码是否正确
     *
     * @param code 验证码
     */
    @Override
    public boolean checkVerifyCode(String code, Integer userId) {
//        Integer userId = getCurrentUserId();
        String key = "EmailCode:" + userId + ":code";
        String redisCode = (String) redisService.getValue(key);
        if (redisCode != null && redisCode.equals(code)) {
            redisService.removeValue(key);
            return true;
        } else {
            return false;
        }
    }

    @Async
    @Override
    public void sendValidateCodeEmail(String receiver, String validateCode) {
        log.info("发送邮件");
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("【非遗传承保护平台】邮箱验证");
        simpleMailMessage.setTo(receiver);
        simpleMailMessage.setFrom(sender);
        // 生成验证码
        simpleMailMessage.setText(
                "验证码："
                        + validateCode
                        + "，本次验证码五分钟内有效，请及时输入。（请勿泄露此验证码）\n"
        );
        sendEmail(simpleMailMessage);
    }

}